//
//  AppDelegate.m
//  UHealth
//
//  Created by gjtxz on 14/12/29.
//  Copyright (c) 2014年 gjtx. All rights reserved.
//asdasd
#import "AppDelegate.h"
#import "LaunchVC.h"

#import "FillInfoVC.h"
#import "HistoryVC.h"
#import "ServiceVC.h"
#import "UserVC.h"
#import "BLEVC.h"
#import "MonitorVC.h"
#import "DataUtil/DBManage.h"
#import "NewHomeViewController.h"
#import "UserInfoViewController.h"
#import "AFNetworking.h"
#import "iToast.h"

#import <ShareSDK/ShareSDK.h>
#import <TencentOpenAPI/QQApiInterface.h>
#import <TencentOpenAPI/TencentOAuth.h>
#import "WXApi.h"
#import "WeiboSDK.h"


@interface AppDelegate ()

@end

static NSString * const kShareSdkAppId           = @"5e918bcf69fa";
static NSString * const kSinaWeiboShareAppId     = @"446197465";
static NSString * const kSinaWeiboShareAppSecret = @"4803bbe227a9ec731867805973b2c840";
static NSString * const kTencentQQShareAppId     = @"";
static NSString * const kTencentWXShareAppId     = @"wxa458d6e37dcda001";


@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    // 监测网络情况
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        NSString *str =@"";
        switch (status) {
            case -1:
                str  = kLocal(@"netNoOk1");
                break;
            case 0:
                str  = kLocal(@"netNoOk");
                break;
            case 1:
                str  = kLocal(@"netNoOk2");
                break;
            case 2:
                str  = kLocal(@"netNoOk3");
                break;
                
            default:
                break;
        }
        kDebug(@"网络状态:%@",str);
    }];
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];

    [self createTables];
    
    [self registerShareSdkSettings];
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
//    self.window.rootViewController = [[LaunchVC alloc]init];
    
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    if ([def boolForKey:@"AlreadyLaunch"]) {
        if (!kNetID) {
            self.window.rootViewController = [[FillInfoVC alloc]init];
        }else{
            [self changRootVCToMain];
        }
    }else{
        self.window.rootViewController = [[LaunchVC alloc]init];
    }
    
//    [self testChangeRootController];
    
//    if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]){
//        [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
//    }
    
    
    if(CURRENT_VERSION>=8.0){//8.0以后使用这种方法来注册推送通知
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        
        UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes];
    }else{
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeBadge)];
    }
    
    
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    return YES;
}

-(void)createTables
{
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    if (![def boolForKey:@"AlreadyCreateDBAndTables"]) {
        DBManage *manager = [DBManage sharedManager];
        BOOL ret0 = [manager createTableWithName:kTemperatureTable];
        BOOL ret1 = [manager createTableWithName:kUserTable];
//        BOOL ret1 = [manager createTableWithName:kBloodSugarTable];
        BOOL ret2 = [manager createTableWithName:kLogTable];
        BOOL ret3 = [manager createTableWithName:kYunTemperatureTable];
//        BOOL ret4 = [manager createTableWithName:kUserDailyTable];
        if ( ret0 ) {
            kDebug(@"kTemperatureTable数据库创建OK");
            [def setBool:YES forKey:@"AlreadyCreateDBAndTables"];
            [def synchronize];
        }
        
        if ( ret1 ){
            kDebug(@"kUserTable数据库创建OK");
            [def setBool:YES forKey:@"AlreadyCreateDBAndTables"];
            [def synchronize];
        }
        
        if ( ret2 ){
            kDebug(@"kLogTable数据库创建OK");
            [def setBool:YES forKey:@"AlreadyCreateDBAndTables"];
            [def synchronize];
        }
        
        if ( ret3 ){
            kDebug(@"kYunTemperatureTable数据库创建OK");
            [def setBool:YES forKey:@"AlreadyCreateDBAndTables"];
            [def synchronize];
        }
    }
}


-(void)changRootVCToLaunch
{
    //清空家庭成员
//    NSString *constr = [NSString stringWithFormat:@"%@ > '0'",kUserId];
//    [[DBManage sharedManager] deleteDataFromTable:kUserTable andConditions:constr];
    
    self.window.rootViewController = [[FillInfoVC alloc]init];
}

-(void)changRootVCToMain
{
    [self getPersonInfo];
    
//    serviceNav.hidesBarsOnSwipe = YES;//上滑隐藏状态栏
//    
//    [serviceNav.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
//    serviceNav.navigationBar.shadowImage = [UIImage new];
//    serviceNav.navigationBar.translucent = YES;
    
    // 1. 体温VC
    NewHomeViewController *newHometCtl = [[NewHomeViewController alloc] initWithNibName:NSStringFromClass([NewHomeViewController class]) bundle:[NSBundle mainBundle]];
    UINavigationController *homeNavCtl = [[UINavigationController alloc]initWithRootViewController:newHometCtl];
    homeNavCtl.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor]};
    homeNavCtl.navigationBar.barTintColor = kBlueColor;
    
    // 2. 监护VC
    UINavigationController *monitorNav = [[UINavigationController alloc]initWithRootViewController:[[MonitorVC alloc]init]];
    monitorNav.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor]};
    monitorNav.navigationBar.barTintColor = kBlueColor;
    
    
    // 3. 历史VC
    UINavigationController *historyNav = [[UINavigationController alloc]initWithRootViewController:[[HistoryVC alloc]init]];
    historyNav.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor]};
    historyNav.navigationBar.barTintColor = kBlueColor;
    
    // 4. 服务VC
    UINavigationController *serviceNav = [[UINavigationController alloc]initWithRootViewController:[[ServiceVC alloc]init]];
    serviceNav.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor]};
    serviceNav.navigationBar.barTintColor = kBlueColor;
    
    UITabBarController *tabBarC = [[UITabBarController alloc]init];
    tabBarC.viewControllers =  @[homeNavCtl, monitorNav, historyNav, serviceNav];
    UITabBar *tabBar = tabBarC.tabBar;
    tabBar.backgroundColor = [UIColor whiteColor];
    
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
    
    self.window.rootViewController = tabBarC;
}

//获取个人资料
-(void) getPersonInfo
{
    if (!kNetID) {
        return;
    }
    if (!kNetIsOK) {
        [[iToast makeText:kLocal(@"netNoOk")] show];
        return;
    }
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer.timeoutInterval = 5;
    manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject: @"text/html"];
    NSString *postStr = [NSString stringWithFormat:@"%@/action/json/userdata.jsp",kBaseUrl];
    NSDictionary *parameters = @{@"action": @"userdata",
                                 @"userid":[NSString stringWithFormat:@"%ld",(long)kNetID],
                                 @"waibai_id":@"0"};
    [manager POST:postStr parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        kDebug(@"个人资料Success: %@", operation.responseString);
        BOOL type = [[responseObject objectForKey:@"type"] boolValue];
        if(type){
            //{"type":true,"msg":"获取成功","jsonarray":[{"id":22120224,"mem_name":"zjw","mem_username":"13049371396","mem_mobile":"13049371396","mem_email":"","mem_weixin":"","mem_sinaweibo":"","mem_headpic":"http://tukang.hanyouapp.com/upload/201502/27/14-43-36_4979_100.png","mem_sex":0,"men_shengao":"0","men_tizhong":"0","mem_birth":"1991-11-30","mem_province":0,"mem_city":0,"mem_area":0}],"famarray":[]}
            
            NSArray *arr = [responseObject objectForKey:@"jsonarray"];
//            UserObj *user = [[UserObj alloc]init];
//            user.userID    = 0;
//            user.headImg   = [arr[0] objectForKey:@"mem_headpic"];
//            user.name      = [arr[0] objectForKey:@"mem_name"];
//            user.sex       = [[arr[0] objectForKey:@"mem_sex"] intValue];
//            user.birthDate = [arr[0] objectForKey:@"mem_birth"];
//            user.height    = [[arr[0] objectForKey:@"men_shengao"] floatValue];
//            user.weight    = [[arr[0] objectForKey:@"men_tizhong"] floatValue];
            
            NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
            [def setObject:[arr[0] objectForKey:@"mem_mobile"] forKey:kNetUserPhone];//手机
            [def synchronize];
            
            //主账号 添加或者更新
//            [[DBManage sharedManager]insertData:user andTable:kUserTable];
            //家庭成员
            //先清空家庭成员
//            NSString *constr = [NSString stringWithFormat:@"%@ > '0'",kUserId];
//            [[DBManage sharedManager] deleteDataFromTable:kUserTable andConditions:constr];
            //再添加家庭成员
            NSArray *farr = [responseObject objectForKey:@"famarray"];
            for (int i = 0; i < farr.count; i++) {
//                if([[farr[i] objectForKey:@"fam_id"] intValue] == user.userID){//过滤主账号
//                    continue;
//                }
                UserObj *u = [[UserObj alloc]init];
                u.userID    = kNetID;
                u.famID     = [[farr[i] objectForKey:@"fam_id"] intValue];
                u.headImg   = [farr[i] objectForKey:@"mem_headpic"];
                u.name      = [farr[i] objectForKey:@"mem_name"];
                u.sex       = [[farr[i] objectForKey:@"mem_sex"] intValue];
                u.birthDate = [farr[i] objectForKey:@"mem_birth"];
                u.height    = [[farr[i] objectForKey:@"men_shengao"] floatValue];
                u.weight    = [[farr[i] objectForKey:@"men_tizhong"] floatValue];
                [[DBManage sharedManager]insertData:u andTable:kUserTable];//添加成员
            }
        }else{//
            
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {//网络失败本地取
        kDebug(@"Error: %@", error);
        [[iToast makeText:kLocal(@"netError")] show];
    }];
}

#pragma mark ShareSDK
- (void)registerShareSdkSettings
{
    [ShareSDK registerApp:kShareSdkAppId];//字符串api20为您的ShareSDK的AppKey
    
    //添加短信分享
    [ShareSDK connectSMS];
    
    [ShareSDK connectMail];
    
    //    //添加QQ应用  注册网址  http://open.qq.com/
    //    [ShareSDK connectQQWithQZoneAppKey:kTencentQQShareAppId
    //                     qqApiInterfaceCls:[QQApiInterface class]
    //                       tencentOAuthCls:[TencentOAuth class]];
    
    //添加微信应用 注册网址 http://open.weixin.qq.com
    [ShareSDK connectWeChatWithAppId:kTencentWXShareAppId
                           wechatCls:[WXApi class]];
}



- (void)testChangeRootController
{
    UserInfoViewController *infoCtl = [[UserInfoViewController alloc] initWithNibName:NSStringFromClass([UserInfoViewController class]) bundle:[NSBundle mainBundle]];
    self.window.rootViewController = infoCtl;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    UIApplication*   app = [UIApplication sharedApplication];
    __block    UIBackgroundTaskIdentifier bgTask;
    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (bgTask != UIBackgroundTaskInvalid)
            {
                bgTask = UIBackgroundTaskInvalid;
            }
        });
    }];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (bgTask != UIBackgroundTaskInvalid)
            {
                bgTask = UIBackgroundTaskInvalid;
            }
        });
    });
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    [application setApplicationIconBadgeNumber:0];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    NSLog(@"%@",notification);
    
}

@end
